package cn.com.thingo.hyintelligent.ui.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;

import com.th.opensdk.openapi.RoomInfo;
import com.th.opensdk.openapi.THOpenSDK;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.bean.EZDeviceInfo;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.com.thingo.hyintelligent.R;
import cn.com.thingo.hyintelligent.base.RootFragment;
import cn.com.thingo.hyintelligent.base.contract.ControlContract;
import cn.com.thingo.hyintelligent.presenter.ControlPresenter;
import cn.com.thingo.hyintelligent.ui.fragment.control.ControlItemFragment;
import cn.com.thingo.hyintelligent.util.LogUtil;
import cn.com.thingo.hyintelligent.util.SPUtils;
import cn.com.thingo.hyintelligent.util.VerifyCodeInput;
import cn.com.thingo.hyintelligent.widget.PlayerLoadingTextView;

/**
 * 控制页面
 */
public class ControlFragment extends RootFragment<ControlPresenter> implements ControlContract.View,
        TabLayout.OnTabSelectedListener {
    @BindView(R.id.control_room_tab)
    TabLayout tabRoom;
    @BindView(R.id.control_device_vp)
    ViewPager vpDevice;
    @BindView(R.id.realplay_sv)
    SurfaceView mSurfaceView;
    @BindView(R.id.realplay_loading)
    PlayerLoadingTextView mPlayerLoadingTextView;
    private THOpenSDK thOpenSDK;
    private List<Fragment> fragments = new ArrayList<>();
    private List<String> titles = new ArrayList<>();

    List<RoomInfo> roomList = new ArrayList<>();

    private EZDeviceInfo mEzDeviceInfo;
    private MessageHandler mMsgHandler;
    private PlayerHandle mPlayerHandler;
    public static final int GET_EZDEVICEINFO_SUCCESS = 8;
    public static final String KEY_TITLE_CAMERA = "titleCamera";
    private String deviceSerial;
    private BroadcastReceiver mReceiver;
    private String verifyCode;
    private EZPlayer ezPlayer;
    private boolean isHide;

    public ControlFragment() {
    }

    public static ControlFragment newInstance() {
        return new ControlFragment();
    }

    @Override
    protected void initEventAndData() {
        super.initEventAndData();
        thOpenSDK = THOpenSDK.getInstance();
        initData();
        initCamera();
        LogUtil.d(">>>>>>>>>>>>>>>>>>>>> oncreate");
    }

    private void initData() {
        initRoom();
        initVp();
    }

    @Override
    public void onResume() {

//        LogUtil.d(">>>>>>>>>>>>>>>>>>>>>2 resume");
//        if (thOpenSDK == null) {
//            thOpenSDK = THOpenSDK.getInstance();
//        }
//        if (titles.size() > 0) {
//            titles.clear();
//            fragments.clear();
//            initData();
//        }

        super.onResume();
        if (ezPlayer != null) {
            ezPlayer.setSurfaceHold(mSurfaceView.getHolder());
            if (!isHide) {
                mPlayerLoadingTextView.setVisibility(View.VISIBLE);
                ezPlayer.startRealPlay();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void initVp() {
        vpDevice.setAdapter(new FragmentStatePagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);
            }
        });
        tabRoom.setupWithViewPager(vpDevice);
    }


    private void initRoom() {
        List<RoomInfo> rooms = thOpenSDK.getRoomList();
        if (rooms != null && rooms.size() > 0) {
            int currentRoomId = rooms.get(0).getRoomId();
            SPUtils.newInstance().put(SPUtils.CURRENT_ROOM_ID, currentRoomId);
            Log.d(">>>>>>>>>>>>>>>>>>", String.valueOf(rooms.size()));
            for (int i = 0; i < rooms.size(); i++) {
                titles.add(rooms.get(i).getRoomName());
                fragments.add(ControlItemFragment.newInstance(rooms.get(i).getRoomId()));
            }
        }
        tabRoom.addOnTabSelectedListener(this);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_control;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int position = tab.getPosition();
        if (roomList.size() > 0) {
            int currentRoomId = roomList.get(position).getRoomId();
            SPUtils.newInstance().put(SPUtils.CURRENT_ROOM_ID, currentRoomId);
            ((ControlItemFragment) (fragments.get(position))).initData();
            vpDevice.setCurrentItem(position);
        }

    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }


    private void initCamera() {
        mPlayerLoadingTextView.setVisibility(View.GONE);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                switch (action) {
                    case MonitorFragment.BROADCAST_FIRST:
                        mEzDeviceInfo = intent.getParcelableExtra(MonitorFragment.BROADCAST_FIRST);
                        verifyCode = SPUtils.newInstance().getString(mEzDeviceInfo.getDeviceSerial());
                        ezPlayer = EZOpenSDK.getInstance().createPlayer(mEzDeviceInfo.getDeviceSerial(), mEzDeviceInfo.getCameraInfoList().get(0).getCameraNo());
                        if (verifyCode != null) {
                            ezPlayer.setPlayVerifyCode(verifyCode);
                            ezPlayer.setSurfaceHold(mSurfaceView.getHolder());
                            ezPlayer.setHandler(mPlayerHandler);

                        } else {

                            VerifyCodeInput.VerifyCodeInputDialog(mContext, new VerifyCodeInput.VerifyCodeInputListener() {
                                @Override
                                public void onInputVerifyCode(String verifyCode) {

                                    ezPlayer.setPlayVerifyCode(verifyCode);
                                    ezPlayer.setSurfaceHold(mSurfaceView.getHolder());
                                    ezPlayer.setHandler(mPlayerHandler);

                                }
                            }).show();
                        }
                        break;
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(MonitorFragment.BROADCAST_FIRST);
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mReceiver, filter);
        mMsgHandler = new MessageHandler();
        mPlayerHandler = new PlayerHandle();
        deviceSerial = SPUtils.newInstance().getString(KEY_TITLE_CAMERA);
        if (deviceSerial != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        mEzDeviceInfo = EZOpenSDK.getInstance().getDeviceInfo(deviceSerial);
                        if (mMsgHandler != null && mEzDeviceInfo != null) {
                            Message msg = Message.obtain();
                            msg.what = GET_EZDEVICEINFO_SUCCESS;
                            mMsgHandler.sendMessage(msg);
                        }
                    } catch (BaseException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }
    }

    private class PlayerHandle extends Handler {


        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS:
                    mPlayerLoadingTextView.setVisibility(View.GONE);
                    if (mEzDeviceInfo != null) {
                        SPUtils.newInstance().put(KEY_TITLE_CAMERA, mEzDeviceInfo.getDeviceSerial());
                    }

                    break;
            }
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isHide = hidden;
        if (!hidden) {
            LogUtil.d(">>>>>>>>>>>>>>>>>>>>>3 hidden");
            if (thOpenSDK == null) {
                thOpenSDK = THOpenSDK.getInstance();
            }
            if (titles.size() > 0) {
                titles.clear();
                fragments.clear();
                initData();
            }
        }
        if (ezPlayer != null) {
            if (hidden) {
                ezPlayer.stopRealPlay();
            } else {
                mPlayerLoadingTextView.setVisibility(View.VISIBLE);
                ezPlayer.startRealPlay();
            }
        }

    }

    private class MessageHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_EZDEVICEINFO_SUCCESS:
                    verifyCode = SPUtils.newInstance().getString(mEzDeviceInfo.getDeviceSerial());
                    ezPlayer = EZOpenSDK.getInstance().createPlayer(mEzDeviceInfo.getDeviceSerial(), mEzDeviceInfo.getCameraInfoList().get(0).getCameraNo());
                    if (verifyCode != null) {
                        mPlayerLoadingTextView.setVisibility(View.VISIBLE);
                        ezPlayer.setPlayVerifyCode(verifyCode);
                        ezPlayer.setSurfaceHold(mSurfaceView.getHolder());
                        ezPlayer.setHandler(mPlayerHandler);
                        ezPlayer.startRealPlay();
                    } else {
                        VerifyCodeInput.VerifyCodeInputDialog(mContext, new VerifyCodeInput.VerifyCodeInputListener() {
                            @Override
                            public void onInputVerifyCode(String verifyCode) {
                                mPlayerLoadingTextView.setVisibility(View.VISIBLE);
                                ezPlayer.setPlayVerifyCode(verifyCode);
                                ezPlayer.setSurfaceHold(mSurfaceView.getHolder());
                                ezPlayer.setHandler(mPlayerHandler);
                                ezPlayer.startRealPlay();

                            }
                        }).show();
                    }
                    break;
            }
        }
    }
}